﻿var express = require('express')
var router = express.Router()
var T = require('zati-utils')
var sso = require('./sso')
var config = require('../config')

// 日志打印格式化方法
var logInfo = require('./log-info')

router.all('/getUserInfo', function (req, res, next) {
  var userInfo = req.session.userInfo || {}
  res.json({ success: true, value: userInfo })
})

router.all('/logout', function (req, res, next) {
  sso.logout(req, res)
})

router.all('*', function (req, res, next) {
  var reqData = req.body || {}
  var url = ''
  url = req.originalUrl.replace(/^\/ajax/i, '')
  if (req.originalUrl.indexOf('http') > -1) {
    url = url.replace(/\/http/g, 'http')
  }
  if (req.body.partnerId) {
    // node端添加一个partnerId参数，不在客户端加，防止篡改
    if (req.session.userInfo) {
      reqData.partnerId = req.session.userInfo.partnerId
    }
  } else if (req.body.condition && req.body.condition.partnerId) {
    // 后台分页组件需要在condition里面那一层加参数。
    if (req.session.userInfo) {
      reqData.condition.partnerId = req.session.userInfo.partnerId
    }
  }
  const ajaxParam = {
    url: url,
    method: req.method || 'POST',
    data: reqData,
    host: config.ajaxHost,
    timeout: 10000,
    headers: {
      'lang': req.cookies['lang'] || 'zh_CN',
      'token': req.session.token || '',
      'X-Requested-With': 'XMLHttpRequest'
    }
  }

  T.ajax(ajaxParam).then((json) => {
    handleSuccess(url, json, req)
    logInfo('success', config.ajaxHost, url, reqData, json)

    res.send(JSON.stringify(json))
  }, (error) => {
    logInfo('error', config.ajaxHost, url, reqData, error)
    res.send(JSON.stringify({ success: false, msg: error }))
  }).catch((error) => {
    logInfo('error', config.ajaxHost, url, reqData, error)
    res.send(JSON.stringify({ success: false, msg: error }))
  }).finally()
})

function handleSuccess (url, json, req) {
  if (url.indexOf('/api/uc/user/updateInfo') === 0) { // 用户基本信息发生变更 需要更新session
    let userInfo = req.session.userInfo
    let data = json.data
    if (json && json.success && data && userInfo) {
      if (data.name) {
        userInfo.name = data.name
      }
      if (data.phoneNumber) {
        userInfo.phoneNumber = data.phoneNumber
      }
    }
  }
}

module.exports = router
